<!--  -->
<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title titleName="部门管理">
        <template slot="btn">
          <el-button class="filter-item" type="primary" icon="el-icon-plus" size="small"
            v-hasPermi="{v:['sys:department:add']}" @click="handleAdd">新增
          </el-button>
        </template>
      </modules-title>
    </div>
    <div style="padding: 20px;">
      <!-- 搜索 -->
      <el-form :inline="true">
        <el-form-item label="部门名称" style="margin-right:40px">
          <el-input v-model="queryParams.department_name" placeholder="请输入部门名称" clearable
            size="small" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" style="margin-right:40px">
          <el-select v-model="queryParams.department_status" placeholder="部门状态" clearable
            size="small">
            <el-option v-for="dict in statusOptions" :key="dict.key" :label="dict.value"
              :value="dict.key" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" icon="el-icon-search" size="small"
            @click="handleQuery">搜索
          </el-button>
          <el-button plain icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table :data="deptList" row-key="id" default-expand-all border size="medium"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="department_name" label="部门名称" />
        <el-table-column prop="department_status" label="状态" align="center">
          <template #default="{row}">
            <span v-if="row.department_status === 1" class="status-color6">启用</span>
            <span v-else class="status-color1">停用</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="create_at">
          <template #default="{row}">
            {{ dateFormat1('yyyy-mm-dd HH:MM:SS',row.created_at)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="medium" type="text" icon="el-icon-edit"
              v-hasPermi="{v:['sys:department:edit']}" @click="handleUpdate(scope.row)">
              修改
            </el-button>
            <el-button size="medium" type="text" icon="el-icon-plus"
              v-hasPermi="{v:['sys:department:add']}" @click="handleAdd(scope.row)">新增
            </el-button>
            <el-button v-if="scope.row.parent_id !== '0'" size="medium" type="text"
              v-hasPermi="{v:['sys:department:delete']}" icon="el-icon-delete" style="color:red"
              @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body
      :before-close="cancel" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上级部门" prop="parentId" v-if="!boole">
              <el-cascader v-model="form.parentId" :options="deptOptions" placeholder="请选择归属部门"
                ref="refHandle" :show-all-levels="false" @change="onChange" :key="isResouceShow"
                :props="{expandTrigger: 'hover', checkStrictly: true ,label:'department_name',value:'id'}">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="department_name">
              <el-input v-model="form.department_name" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="principal">
              <el-input v-model="form.principal" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态" prop="departmentStatus">
              <el-radio-group v-model="form.departmentStatus">
                <el-radio v-for="dict in statusOptions" :key="dict.key" :label="dict.key">
                  {{ dict.value }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { depaList, depaAdd, depaUpdate, depaDelete } from "@/api/authorization";
export default {
  data() {
    return {
      queryParams: {
        department_name: "",
        department_status: null
      },
      listArr: [],
      deptList: [],
      title: "",
      open: false,
      form: {},
      rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        tel: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        departmentStatus: [
          { required: true, message: "请选择部门状态", trigger: "change" }
        ],
        department_name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ]
      },
      deptOptions: [],
      statusOptions: [
        { key: -1, value: "停用" },
        { key: 1, value: "启用" }
      ],
      type: true,
      parentIdList: undefined,
      boole: false,
      isResouceShow: 0
    };
  },
  //是计算属性，也可以理解为一个方法。
  computed: {},
  //属性是手动定义的所需监听的值
  watch: {},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.handleDepa();
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    setInterval(function() {
      document.querySelectorAll(".el-cascader-node__label").forEach(el => {
        el.onclick = function() {
          if (this.previousElementSibling) this.previousElementSibling.click();
        };
      });
    }, 1000);
  },
  //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，未调用不会执行，只执行逻辑，返回值可有可无
  methods: {
    //获取部门列表
    handleDepa() {
      depaList(this.queryParams).then(res => {
        if (res.code === 200) {
          this.deptList = res.data || [];
          this.deptOptions = res.data || [];
          ++this.isResouceShow;
        }
      });
    },
    //搜索按钮操作
    handleQuery() {
      depaList(this.queryParams).then(res => {
        if (res.code === 200) {
          this.deptList = this.setTreeData(res.data) || [];
        }
      });
    },
    //重置
    resetQuery() {
      this.queryParams = {
        department_name: "",
        department_status: null
      };
      this.handleDepa();
    },
    //新增按钮操作
    handleAdd(row) {
      this.reset();
      console.log(row);
      if (row.id != undefined && row.parent_id !== "0") {
        this.form.id = row.id;
        this.form.parentId = this.recursive(this.deptOptions, row.parent_id);
      } else {
        this.form.id = "0";
      }
      this.open = true;
      this.title = "添加部门";
      this.type = true;
    },
    //修改按钮操作
    handleUpdate(row) {
      console.log(this.form);
      this.open = true;
      this.title = "修改部门";
      this.type = false;
      if (row.parent_id === "0") {
        this.parentIdList = "0";
        this.boole = true;
      } else {
        this.parentIdList = this.recursive(this.deptOptions, row.parent_id);
        this.boole = false;
      }
      this.form = {
        department_name: row.department_name,
        principal: row.principal,
        tel: row.tel,
        email: row.email,
        departmentStatus:
          row.department_status === 0 ? undefined : row.department_status,
        parentId: this.parentIdList,
        id: row.id
      };
    },
    //删除按钮操作
    handleDelete(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          depaDelete(row.id).then(res => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.handleDepa();
              this.$store.dispatch("user/depaList");
            }else{
              this.$message.error(res.msg)
            }
          });
        })
        .catch(() => {});
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.boole = false;
      this.reset();
    },
    setTreeData(arr) {
      // 删除所有的children,以防止多次调用
      arr.forEach(function(item) {
        delete item.children;
      });
      let map = {}; //构建map
      arr.forEach(i => {
        map[i.id] = i; //构建以id为键 当前数据为值
      });
      let treeData = [];
      arr.forEach(child => {
        const mapItem = map[child.parent_id]; //判断当前数据的parentId是否存在map中
        if (mapItem) {
          (mapItem.children || (mapItem.children = [])).push(child); //这里判断mapItem中是否存在child
        } else {
          treeData.push(child);
        }
      });
      return treeData;
    },
    // 表单重置
    reset() {
      this.form = {
        id: "",
        parentId: "",
        department_name: "",
        principal: "",
        tel: "",
        email: "",
        departmentStatus: null
      };
      this.resetForm("form");
    },
    //提交按钮
    submitForm() {
      let self = this;
      if (self.form.parentId && self.form.parentId instanceof Array) {
        self.form.parentId = self.form.parentId[self.form.parentId.length - 1];
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          let a = JSON.stringify(self.form)
            .replace(/departmentStatus/g, "department_status")
            .replace(/parentId/g, "parent_id");
          let data = JSON.parse(a);
          console.log();
          if (self.type === true) {
            depaAdd(data).then(res => {
              if (res.code === 200) {
                self.$message.success("新增成功");
                self.open = false;
                self.type = true;
                self.handleDepa();
                this.$store.dispatch("user/depaList");
              } else {
                self.$message.error(res.msg);
              }
            });
          } else {
            console.log(data);
            depaUpdate(data, data.id).then(res => {
              if (res.code === 200) {
                self.$message.success("更新成功");
                self.open = false;
                self.type = true;
                self.handleDepa();
                this.$store.dispatch("user/depaList");
              } else {
                self.$message.error(res.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    //单选选择任意一级选项
    cascaderChange(val) {},
    //弹框部门
    onChange(val) {
      if (val !== null && val) {
        this.$refs.refHandle.dropDownVisible = false;
        this.form.parentId = val[val.length - 1];
        this.$refs.form.fields.map(i => {
          if (i.prop === "parentId") {
            i.clearValidate();
          }
        });
      }
    },
    //递归部门
    recursive(arr, id) {
      let list = [];
      let self = this;
      for (let i = 0; i < arr.length; i++) {
        if (id === arr[i].id) {
          list.push(arr[i].id);
          return list;
        } else if (arr[i].children && arr[i].children.length > 0) {
          let list1 = this.recursive(arr[i].children, id);
          if (list1 && list1.length > 0) {
            list.push(arr[i].id);
            return (list = list.concat(list1));
          }
        }
      }
    }
  }
};
</script>
<style scoped>
/* @import url(); 引入css类 */
::v-deep .el-button--medium {
  padding: 0;
}
</style>

